<template>
  <div>
    <a-layout>
      <div class="rs-header">
        <div class="rs-header_tab">
          <div class="rs-header_tab_selector">
            <a-select
              default-value="请选择学院"
              size="small"
              style="width: 200px"
              @change="collegeChange"
            >
              <a-select-option
                v-for="sName in sugOrgList"
                :value="sName.subOrgName"
                :key="sName.subOrgName"
              >
                {{ sName.subOrgName }}
              </a-select-option>
            </a-select>
          </div>
          <div class="rs-header_tab_selector">
            <a-select
              default-value="请选择教师"
              size="small"
              style="width: 200px"
              @change="peopleChange"
              :disabled="peopleSwitch"
            >
              <a-select-option
                v-for="iTeacher in instructorList"
                :value="iTeacher._id"
                :key="iTeacher._id"
              >
                {{ iTeacher.name }} | {{ iTeacher.title }}
              </a-select-option>
            </a-select>
          </div>
          <div class="rs-header_tab_selector">
                <a-input-search placeholder="请输入你想搜索的文件名" size="small" v-model="searchItem"  @search="onSearch"/>
          </div>
        </div>
      </div>
      <a-layout-content
        :style="{
          minHeight: '280px',
        }"
      >
        <a-tabs default-active-key="0" @change="btnVisible">
          <a-tab-pane key="0" tab="教学资源">
            <a-table
              rowKey="_id"
              size="small"
              :pagination="{
                total: courseResourceList.length,
                defaultPageSize: 20,
                'hide-on-single-page': true,
              }"
              :bordered="true"
              :columns="columns"
              :data-source="courseResourceList"
            >
              <span slot="action" slot-scope="text, record">
                <a @click="download(record)">下载</a>
                <a-divider type="vertical" />
                <a
                  @click="deleteResource(record._id)"
                  >删除</a
                >
                 <!-- v-show="isShowDeleteButton === 'yes'"-->
              </span>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="1" tab="视频资源">
            <a-table
              rowKey="_id"
              size="small"
              :pagination="{
                total: videoList.length,
                defaultPageSize: 20,
                'hide-on-single-page': true,
              }"
              :bordered="true"
              :columns="columns"
              :data-source="videoList"
              v-if="table_view"
            >
              <span slot="action" slot-scope="text, record">
                <a @click="download(record)">下载</a>
                <a-divider type="vertical" />
                <a
                  @click="deleteResource(record._id)"
                  >删除</a>
                  <!-- v-show="isShowDeleteButton === 'yes'"-->
              </span>
            </a-table>
            <div v-else class="vedioContent" >
              <div :key="index" class="rs-block" v-for="(video,index) in videoList">
                <a-tooltip>
                <img
                  class="rs-block-ppt"
                  src="../../../../src/assets/img/SVGS/video.svg"
                  alt="logo"
                />
                <div class="b-title">
                  {{ video.name }}
                </div>
                <template slot="title">
                  <p>上传者:{{video.authorId.name}}</p>
                  <p>大小:{{video.size}}</p>
                </template>
                </a-tooltip>
              </div>
            </div>
            <!--
            <div v-else class="vedioContent" >
              <div class="vedioList" v-for="vedio in videoList" :key="vedio._id">
                <a-tooltip  placement="top"  overlayClassName="hoverCard" >
                  <video class="vedio" >
                    <source :src="vedio.url" type="video/mp4" />
                  </video>
                  <template slot="title">
                    <p>上传者:{{vedio.authorId.name}}</p>
                    <p>大小:{{vedio.size}}</p>
                  </template>
                </a-tooltip>
                <div>
                  <div class="describe">
                    <p>
                      {{ vedio.name }}.{{vedio.rsType}}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          -->
          </a-tab-pane>
          <span 
            slot="tabBarExtraContent" 
            v-if="view_btn_visible" 
            class="view_btn"
            style="border: 0; margin-right: 15px; color:#4ABAC4" 
            @click="ChangetoView"
          >
            <a-icon type="appstore"  />
          </span>
          <span 
            slot="tabBarExtraContent" 
            v-if="view_btn_visible" 
            class="table_btn"
            style="border: 0; margin-right: 20px;" 
            @click="ChangetoTable"
          >
            <a-icon type="unordered-list" />
          </span>
        </a-tabs>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script>
const columns = [
  {
    title: "文件名",
    dataIndex: "name",
    align: "center",
    width: "200px",
    key: "_id",
  },
  {
    title: "上传者",
    dataIndex: "authorId.name",
    align: "center",
    width: "150px",
    key: "authorId.name",
  },
  {
    title: "大小",
    dataIndex: "size",
    width: "150px",
    align: "center",
    key: "size",
  },
  {
    title: "类型",
    dataIndex: "rsType",
    align: "center",
    key: "rsType",
  },
  {
    title: "标签",
    key: "tags",
    dataIndex: "tags",
    align: "center",
    scopedSlots: { customRender: "tags" },
  },
  {
    title: "下载次数",
    key: "click",
    align: "center",
    dataIndex: "click",
  },
  {
    title: "操作",
    key: "action",
    align: "center",
    scopedSlots: { customRender: "action" },
  },
];

const data = [];

import axiosInstance from "../../../utils/axios.js";
import { mapState } from "vuex";
import * as TransformSize from "@/utils/transform";

export default {
  data() {
    return {
      size: "default",
      sugOrgList: [],
      instructorList: [],
      resourceList: [],
      searchList:[],
      data,
      columns,
      peopleSwitch: false,
      currentCollege: "",
      currentTeacher: "",
      refresh: 0,
     // isShowDeleteButton: "yes1",
      view_btn_visible: false,
      table_view: false,
      searchItem:"",
    };
  },
  watch: {
    refresh(val) {
      this.getResources(this.currentCollege, this.currentTeacher);
    },
  },
  methods: {
    btnVisible() {
      this.view_btn_visible = !this.view_btn_visible;
    },
    ChangetoTable() {
      this.table_view = true;
      document.getElementsByClassName("table_btn")[0].style.color="#4ABAC4";
      document.getElementsByClassName("view_btn")[0].style.color="";
    },
    ChangetoView() {
      this.table_view = false;
      document.getElementsByClassName("view_btn")[0].style.color="#4ABAC4";
      document.getElementsByClassName("table_btn")[0].style.color="";
    },
    TransformFileSize() {
      this.resourceList.forEach((resource) => {
        resource.size = TransformSize.tranformFileSizeTOKB(resource.size);
      });
    },
    collegeChange(value) {
      console.log(`Selected: ${value}`);
      // if switch close, just check resource of college
      this.currentCollege = value;
     // this.isShowDeleteButton = "no";
      //if switch open, do NOTHING
      this.getTeacherName(this.currentCollege);
      this.getResourcesOfSubOrg(this.currentCollege);
    },
    peopleChange(value) {
      console.log(`Selected: ${value}`);
      this.currentTeacher = value;
     // this.isShowDeleteButton = "yes";
      //if switch open, check out resource of people in college
      this.getResources(this.currentCollege, this.currentTeacher);
    },

    deleteResource(resourceId) {
      const that = this;
      this.$confirm({
        title: "确定删除此资源吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          try {
            that.$store
              .dispatch("admin/deleteResourceById", resourceId)
              .then((res) => {
                console.log(`res------:${res}`);
                that.refresh += 1;
              })
              .catch((err) => {
                console.log(err);
              });
          } catch (err) {
            console.log(err);
          }
        },
        onCancel() {
          // console.log("Cancel");
        },
      });
    },
    download(source) {
      let a = document.createElement("a");
      let event = new MouseEvent("click");
      a.download = source.name;
      a.target = "_blank";
      a.href = source.url;
      a.dispatchEvent(event);
    },

    getResourcesOfSubOrg(subOrgName) {
      this.$store
        .dispatch("admin/getResourcesOfOneCollege", {
          org_name: this.org_name,
          subOrg_name: subOrgName,
        })
        .then((res) => {
          this.resourceList = res.data.allResources;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // async
    getSubOrgsName() {
      const orgId = this.oid; ///////////////
      const url = "/pc/v1/organizations/" + orgId + "/suborgs";
      this.$store
        .dispatch("admin/getTreeByURLwithSpin", url)
        .then((response) => {
          this.sugOrgList = response.data.subOrgs;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // async
    getTeacherName(subOrgName) {
      // const orgId="5facabb2cf3bb2002b4b3f38"
      const queryObject = {
        org_name: this.org_name,
        subOrg_name: subOrgName,
        role: "teacher",
      };
      let queryString = "";
      Object.keys(queryObject).forEach((key) => {
        queryString += key + "=" + queryObject[key] + "&";
      });

      queryString = "?" + queryString.slice(0, -1);

      const url = "/pc/v1/users/multipleUsers" + queryString;
      // console.log(url);
      this.$store
        .dispatch("admin/getTreeByURLwithSpin", url)
        .then((response) => {
          // console.log(response);
          this.instructorList = response.data.teachers;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    async getAllresources() {
      this.$store
        .dispatch("admin/getAllResources")
        .then((response) => {
          this.resourceList = response.data.resources;
          this.searchList=response.data.resources;
          this.TransformFileSize();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    async getResources(college, teacher) {
      const queryObject = {
        authorId: teacher, ////////////////////////////
      };
      let queryString = "";
      Object.keys(queryObject).forEach((key) => {
        queryString += key + "=" + queryObject[key] + "&";
      });
      queryString = "?" + queryString.slice(0, -1);
      const url = "/pc/v1/resources" + queryString;
      this.$store
        .dispatch("admin/getTreeByURL", url)
        .then((response) => {
          // console.log("---------");
          // console.log(response);
          this.resourceList = response.data.resources;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    onSearch(){
     if(!this.searchItem )  this.resourceList=this.searchList;
     else{
      this.resourceList=this.searchList.filter((resource) => {
        return resource.name.includes(this.searchItem);
      });
     }
      console.log(this.resourceList);
    },
  },
  computed: {
    videoList() {
      return this.resourceList.filter((resource) => {
        return resource.rsType == "mp4";
      });
    },
    courseResourceList() {
      return this.resourceList.filter((resource) => {
        return resource.rsType != "mp4";
      });
    },
    ...mapState({
      oid: (state) => state.public.oid,
      uid: (state) => state.public.uid,
      org_name: (state) => state.public.orgName,
    }),
  },
  created: function () {},
  mounted() {
    this.getAllresources();

    this.getSubOrgsName();
    this.getTeacherName();
    this.$store.dispatch("public/getOrgnizationName", this.oid);
  },
};
</script>

<style lang="scss">
.temp {
  display: flex;
  flex-direction: column;
}
::v-deep .ant-table-row {
  padding-top: 0;
}

::v-deep .ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0;
}

::v-deep
  .ant-table-small
  > .ant-table-content
  > .ant-table-body
  > table
  > .ant-table-tbody
  > tr
  > td {
  padding: 5px 5px;
}
.vedioContent {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.vedioList {
  width: 150px;
  height: 100px;
  padding: 0px 0px;
  margin: 10px 10px;
  /* background:black; */
}
.vedio {
  width: 150px;
  height: 90px;
  display: block;
  background-image: url("C:\Users\user\Desktop\大学\教学小栈\learning-management-world\stack-client\src\assets\img\video\notLiving.jpg");
  background-size: 150px 90px;
  cursor: pointer;
}
.describe {
  text-align: center;
  padding: 0;
}
/* 悬浮卡片样式 */
.hoverCard{
  width: 150px;
  height:80px;
  font-size: 12px;
}
.describe >p{
  /* 溢出文本处理 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.rs-block-ppt {
  width: 100%;
  position: relative;
  top: -10px;
  z-index: 3;
  /* color: #000000a6; */
}
.b-title {
  position: relative;
  bottom: 20px;
  height: 18px;
  background-color: rgba(#101d2c, 0.8);
  color: white;
  text-align: center;
  font-size: 12px;
  border-radius: 3px;
  z-index: 5;
}
.rs-block {
  width: 80px;
  height: 100px;
  margin-left: 30px;
  margin-top: 10px;
  margin-bottom: 10px;
  background-color: #f9f7f6;
  border: 1px solid #eee;
  border-radius: 3px;
}
</style>
